import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

//只要仓库数据变，视图也会变
export default new Vuex.Store({
  state: {
    goodsList: [],
  }, //仓库数据本身
  mutations: {
    CHANGELIST(state, data) {
      state.goodsList = data.data;
    },
    ADD(state, data) {
      let arr = state.goodsList;
      arr.forEach((v) => {
        v.foods.forEach((v2) => {
          if (v2.id === data.value) {
            v2.num++;
          }
        });
      });
    },
    Less(state, data) {
      let arr = state.goodsList;
      arr.forEach((v) => {
        v.foods.forEach((v2) => {
          if (v2.id === data.value) {
            v2.num--;
          }
        });
      });
    },
    CLEAR(state) {
      let arr = state.goodsList;
      arr.forEach((v) => {
        v.foods.forEach((v2) => {
          v2.num = 0;
        });
      });
    },
  }, //修改仓库数据的唯一方式
  getters: {
    cars(state) {
      let arr = [];
      console.log(state);
      state.goodsList.forEach((v) => {
        v.foods.forEach((v2) => {
          if (v2.num > 0) {
            arr.push(v2);
          }
        });
      });
      return arr;
    },

    total(state) {
      let total = 0;
      let arr = state.goodsList;
      console.log(arr);
      arr.forEach((v) => {
        v.foods.forEach((v2) => {
          if (v2.num > 0) {
            total += v2.num;
          }
        });
      });
      return total;
      //   total += item.num;
    },
    price(state) {
      let total = 0;
      console.log(state.goodsList);
      state.goodsList.forEach((v) => {
        v.foods.forEach((v2) => {
          if (v2.num > 0) {
            total += v2.price * v2.num;
          }
        });
      });
      return total;
      //   total += item.num;
    },
  }, //仓库中的计算属性
  /*了解*/
  actions: {}, //异步修改仓库
  modules: {}, //合并状态机
});
